import type { ConfigEnv } from 'vite'
import pkg from './package.json'
import dayjs from 'dayjs'
import { resolve } from 'path'
import { createVitePlugins } from './build/vite/plugin'
import { createProxy } from './build/vite/proxy'
import { loadEnv, defineConfig } from 'vite'
import { OUTPUT_DIR } from './build/constant'
import { wrapperEnv } from './build/utils'
import { generateModifyVars } from './build/generate/generateModifyVars'

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir)
}

const { dependencies, devDependencies, name, version } = pkg
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
}

export default ({ mode, command }: ConfigEnv) => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env)

  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_DROP_CONSOLE } = viteEnv

  const isBuild = command === 'build'
  return defineConfig({
    base: VITE_PUBLIC_PATH, // 读取环境变量
    root,
    // 别名配置
    resolve: {
      alias: [
        // /@/xxxx => src/xxxx
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.js',
        },
        {
          find: /\/@\//,
          replacement: pathResolve('src') + '/',
        },
        {
          find: /@\//,
          replacement: pathResolve('src') + '/',
        },
        // /#/xxxx => types/xxxx
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
        {
          find: /#\//,
          replacement: pathResolve('types') + '/',
        },
        { find: /^~/, replacement: '' },
      ],
      extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue', '.less'],
    },
    // The vite plugin used by the project. The quantity is large, so it is separately extracted and managed
    plugins: createVitePlugins(viteEnv, isBuild),
    server: {
      https: false,
      // Listening on all local IPs
      host: true,
      port: VITE_PORT,
      proxy: createProxy(VITE_PROXY),
    },
    esbuild: {
      pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
      jsxFactory: 'h',
      jsxFragment: 'Fragment',
      jsxInject: "import { h } from 'vue';",
      include: ['.js', '.jsx', '.tsx'],
    },
    build: {
      target: 'es2015',
      cssTarget: 'chrome80',
      outDir: OUTPUT_DIR,
      chunkSizeWarningLimit: 2000,
      commonjsOptions: {
        include: [/node_modules/],
        transformMixedEsModules: true,
      },
    },
    // vite报错 process is not defined
    define: {
      'process.env': process.env,
      // setting vue-i18-next
      // Suppress warning
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    css: {
      // 定位css文件
      preprocessorOptions: {
        less: {
          modifyVars: generateModifyVars(),
          // DO NOT REMOVE THIS LINE
          javascriptEnabled: true,
        },
      },
      modules: false,
    },
    optimizeDeps: {
      // @iconify/iconify: The dependency is dynamically and virtually loaded by @purge-icons/generated, so it needs to be specified explicitly
      include: [
        '@vue/runtime-core',
        '@vue/shared',
        '@iconify/iconify',
        'ant-design-vue/es/locale/zh_CN',
        'ant-design-vue/es/locale/en_US',
      ],
    },
  })
}
